package io.terminus.lego.shinda.web.oauth2.provider

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler
import org.springframework.security.oauth2.provider.token.TokenStore
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
import javax.sql.DataSource


/**
 * 授权配置
 * @author wangmeng
 * @date 2018/4/12
 */
@Configuration
@EnableAuthorizationServer
class AuthorizationConfig @Autowired constructor(val dataSource: DataSource,
                                                 val tokenStore: TokenStore,
                                                 val userApprovalHandler: UserApprovalHandler?,
                                                 val accessTokenConverter: JwtAccessTokenConverter,
                                                 @Qualifier("authenticationManagerBean")
                                                 val authenticationManager: AuthenticationManager?) : AuthorizationServerConfigurerAdapter() {

    @Throws(Exception::class)
    override fun configure(clients: ClientDetailsServiceConfigurer) {
        // @formatter:off
        clients.jdbc(dataSource)
        // @formatter:on
    }


    @Throws(Exception::class)
    override fun configure(endpoints: AuthorizationServerEndpointsConfigurer) {
        endpoints.userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter)
    }

    @Throws(Exception::class)
    override fun configure(oauthServer: AuthorizationServerSecurityConfigurer?) {
        oauthServer!!.realm("sparklr2/client")
    }

}